# /**
# * Copyright (c) 2022 Beijing Jiaotong University
# * PhotLab is licensed under [Open Source License].
# * You can use this software according to the terms and conditions of the [Open Source License].
# *
# * You may obtain a copy of [Open Source License] at: [https://open.source.license/]
# *
# * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# *
# * See the [Open Source License] for more details.
# */
# /**
# * Author: Shihao Xie
# * Created: Jul. 6, 2022
# * Supported by: National Key Research and Development Program of China
# */
import sys
import logging.config
from logging import FileHandler, Filter
import os
from phot_server.server_config.global_config import LOGGER_CONFIG_ROOT, LOG_FILE_ROOT

log_file_path = LOGGER_CONFIG_ROOT
# set logging configuration
logging.config.fileConfig(log_file_path)
# get logger of root
root_logger = logging.getLogger("root")
if not os.path.exists(LOG_FILE_ROOT):
    os.makedirs(LOG_FILE_ROOT, 0o777)
root_handler = FileHandler(os.path.join(LOG_FILE_ROOT, "./root.log"), encoding="utf-8")
root_handler.setFormatter(logging.Formatter("%(asctime)s - %(message)s"))
root_logger.addHandler(root_handler)

logger = logging.getLogger("phot_server")
server_handler = FileHandler(os.path.join(LOG_FILE_ROOT, "./phot_server.log"), encoding="utf-8")
server_handler.setFormatter(logging.Formatter("%(asctime)s - %(message)s"))
server_handler.addFilter(Filter(name="phot_server"))
server_handler.setLevel(logging.INFO)
logger.addHandler(server_handler)
logger.propagate = 0

phot_logger = logging.getLogger("phot")
phot_handler = FileHandler(os.path.join(LOG_FILE_ROOT, "./phot.log"), encoding="utf-8")
phot_handler.setFormatter(logging.Formatter("%(asctime)s - %(message)s"))
phot_handler.addFilter(Filter(name="phot"))
phot_logger.addHandler(phot_handler)

engine_logger = logging.getLogger("phot_engine")
engine_handler = FileHandler(os.path.join(LOG_FILE_ROOT, "./phot_engine.log"), encoding="utf-8")
engine_handler.setFormatter(logging.Formatter("%(asctime)s - %(message)s"))
engine_handler.addFilter(Filter(name="phot_engine"))
engine_logger.addHandler(engine_handler)


def get_log_file_end(name: str):
    eof = 0
    with open(os.path.join(LOG_FILE_ROOT, name + ".log"), "r", encoding="utf-8") as f:
        f.seek(0, 2)
        eof = f.tell()
    return eof
